import { cloneDeep,uniqBy } from 'lodash'
import { parse } from 'qs'
import { message } from 'antd'
import { Link, hashHistory } from 'dva/router'
import {
  getCommunity,
  saveCommunityOrUpdate
} from './oldCommunityEditServ'

const defultState = {
  btnLoading: false,
  requestUrl: '',
  roleList: [],
  test: '1',
  detail: {},
  sellerList: [],
  areaList: [],
  addressList:[],
  selectItem: [],
  userInfor: {},
  role: [],
  accountId: '',
  query: {
    accountId: '',
    permissionRoleIds: [],
    productIds: [],
  }
}

const tmpModule = {
  state: cloneDeep(defultState),
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({pathname, query}) => {
        if ('' + tmpModule.pathname === '' + pathname) {
          dispatch({ type: 'updateStore', payload: cloneDeep(defultState) });
          // 执行业务操作
          let {communityId} = query
          if(communityId){
            dispatch({type: 'getDetail', payload: {id: communityId}})
          }
        }
      })
    }
  },
  
  effects: {    
    * update ({payload}, {put, select, call}) {
        console.log(payload,"_-----------------");
        let {detail} = payload
        let {data, success, msg} = yield call(saveCommunityOrUpdate, detail)
        if (success) {
          detail = {}
          yield put({type: 'updateStore', payload: {detail}})
          if(payload.detail.id){
            message.success('编辑成功').then(() => {
              hashHistory.push('/home/buildingAdmin/oldCommunity')
            })
          }else{
            message.success('新增成功').then(() => {
              hashHistory.push('/home/buildingAdmin/oldCommunity')
            })
          }
          
        } else {
          message.error(msg)
        }
    },

    * getDetail ({payload}, {put, select, call}) {
      try {
        let {data, success} = yield call(getCommunity, payload)
        let detail = {}
        if (success) {
          detail = data
          yield put({type: 'updateStore', payload: {detail}})
        }
      } catch (e) {
        console.error(e)
      }
    },
  },
  
  reducers: {
    updateStore (preState, action) {
      return {...preState, ...action.payload}
    }
  }
}

export default tmpModule
